<?php

class Listing_Form_PostAnAddRegularForm extends Listing_Form_PostAnAddForm
{
    private $_preview_link = '';

    private $_category;
    private $_adid;
    private $_listing;

    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementDecorators = array(
        'ViewHelper',
    );

    protected $formDecorators = array(
        'PrepareElements',
        array('ViewScript', array('viewScript' => 'index/customization/regular-post-an-ad.phtml'))
    );

    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
        array('HtmlTag', array('tag' => 'p', 'class' => 'price radio text')),
        array('Description', array('placement' => 'prepend', 'tag' => 'label')),
    );

    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'APPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    public function __construct($options = array())
    {
        $this->_preview_link = !empty($options['preview_link']) ? $options['preview_link'] : '';
        $this->_category = !empty($options['category']) ? $options['category'] : array();
        $this->_adid = !empty($options['adid']) ? $options['adid'] : array();
        $this->_listing = !empty($options['listing']) ? $options['listing'] : new StdClass();
        parent::__construct();
    }
    
    public function init()
    {
        parent::init();

        /*
        $this->addElement('text', 'category0', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'required'   => false,
        ));

        $this->getElement('category0')->setValue((string)$this->_category[0]);

        var_dump((string)$this->_category[0]);
        */
        $element = new Zend_Form_Element_Text('adid');
        $element->setValue((string) $this->_adid);
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        
        $this->addElement($element);

        $this->addElement('text', 'tl_en', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '星号栏必须填写')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => true,
            'label'      => 'Title:',
        ));

        $this->addElement('textarea', 'cs_en', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '星号栏必须填写')),
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'description textarea')))),
            'rows'=>'',
            'required'   => true,
            'label'      => 'Description:',
        ));

        $this->addElement('text', 'price_text_value', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Float', true, array('messages' => 'Numbers Only')),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Title:',
        ));

        $this->addElement('radio', 'price', array(
            'filters'      => array('StringTrim'),
            'escape'       => false,
            'separator'    => '',
            'multiOptions' => array(
              1 => '元', 2 => '免费', 3 => '联络卖家'
            ),
            'Description' => 'Price',
            'label_id'    => 'label_price',
            'decorators' => $this->elementDecorators,
            'validators' => array(
                'Int'
            ),
            'required'   => true,
        ));

        
        if (empty($_POST['area_l1'])) {
            $selected_area = "";
            if (!empty($this->_listing)) {
                if (empty($selected_area)) {
                    $loc = $this->_listing->area_l2;
                    if (!empty($loc)) {
                        $selected_area = (string)$loc->getParent()->_id;
                    }
                }
            }
        }
        else {
            $selected_area = $_POST['area_l1'];
        }
        $areas = Model_Location::getAreaL1PostAd();
        if (empty($selected_area)) {
            reset($areas);
            $selected_area = key($areas);
        }
        $this->addElement('select', 'area_l1', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => $areas,
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));

        //District
        $this->addElement('select', 'area_l2', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => Model_Location::getAreaL2PostAd($selected_area),
            //'disableLoadDefaultDecorators' => true,
            //'decorators' => $this->elementDecorators,
            'decorators'   => array(
                'ViewHelper',
                //'Errors',
                array('Label', array()),
            ),
            'required'   => false,
        ));

        //$this->getElement('area_l2')->setOptions(array('disabled'=>'disabled'));
        
        //location flag
        $this->addElement('radio', 'loc_flag', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => array(
                'chi' => '中国+香港+澳门',
                'mchi' => '中国大陆',
            ),
            'separator' => '',
            //'value' => '0',
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        

        /*$this->addElement('textarea', 'st_en', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Street address:',
        ));*/
        $this->addElement('text', 'st_en', array(
       	 	'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Street address:',
        ));
        
        $this->addElement('text', 'tag', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Tag:',
        ));
        
        $this->addElement('text', 'remark', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Remark:',
        ));
        
        $this->addElement('text', 'c_name', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Contact Name:',
        ));
        
        $this->addElement('checkbox', 'agent', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'c_tel', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Contact Tel:',
        ));
        
        $this->addElement('text', 'c_msn', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'MSN / QQ:',
        ));
        
        $this->addElement('button', 'validate', array(
            'required'    => false,
            'ignore'      => true,
            'label'       => 'Post your ad2', 
            'decorators' => $this->elementDecorators,
        ));

        $this->addElement('button', 'preview', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'button',
            'label'       => 'Preview',
            //'description' => '<a href="'.$this->_preview_link.'">Preview</a>',
            'decorators' => $this->elementDecorators,
            //'decorators'  => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'preview button')))),
        ));

        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['category'] = $this->_category;
        $opt['adid'] = $this->_adid;
        $opt['listing'] = $this->_listing;
        $opt['preview_link'] = $this->_preview_link;
        
        $this->getDecorator('ViewScript')->setOptions($opt);
    }

    public function populate(array $arr)
    {
		if (Zend_Registry::get('current_language') == 'en'){
			$ft = 'en';
			$tt = 'zh-TW';
			
            $this->getElement('tl_en')->setValue($this->_listing->tl_en);
			$this->getElement('cs_en')->setValue($this->_listing->cs_en);
			$this->getElement('st_en')->setValue((string)$this->_listing->st_en);
			
			
		} else {
			$ft = 'zh-TW';
			$tt = 'en';
			
			$this->getElement('tl_en')->setValue($this->_listing->tl_sc);
            $this->getElement('cs_en')->setValue($this->_listing->cs_sc);
            $this->getElement('st_en')->setValue((string) $this->_listing->st_sc);
			
		}
		
        if(empty($arr['price'])) {
            if (!empty($this->_listing->is_free)) {
                $this->getElement('price')->setValue(2);
            }elseif (!empty($this->_listing->is_contact)) {
                $this->getElement('price')->setValue(3);
            }else {
                $this->getElement('price')->setValue(1);
                $this->getElement('price_text_value')->setValue($this->_listing->price);
            }
        }

        //Area
        if (empty($arr['area_l1'])) {
        	$selected_area = '';
            if (empty($selected_area)) {	
                $loc = $this->_listing->area_l2;
                if (!empty($loc)) {	
                    $selected_area = (string)$loc->getParent()->_id;
                }
            }            
            $this->getElement('area_l1')->setValue((string)$selected_area);
        }
		
        //District
        if (empty($arr['area_l2'])) {
            if (!empty($this->_listing->arl2)) {
                $this->getElement('area_l2')->setValue((string)$this->_listing->arl2);
            }            
        }
        
        if (empty($arr['tag'])) {
        	if(!empty($this->_listing->tags)){
				$this->getElement('tag')->setValue(implode(',', $this->_listing->tags));
			}            
        }
        
        if (empty($arr['remark'])) {
            $this->getElement('remark')->setValue((string)$this->_listing->remark);
        }
        
        if (empty($arr['c_name'])) {
            $this->getElement('c_name')->setValue((string)$this->_listing->c_name);
        }
        
        if (empty($arr['c_tel'])) {
            $this->getElement('c_tel')->setValue((string)$this->_listing->c_tel);
        }
        
        if (empty($arr['c_msn'])) {
            $this->getElement('c_msn')->setValue((string)$this->_listing->c_msn);
        }
        
        parent::populate($arr);
        return $arr;
    }

    public function save($preview = false)
    {
        if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }
        //echo '<pre>';var_dump($this->_adid);exit;
				
        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            if ($user->role == Model_User::ROLE_ADMIN) {
                if(empty($ad->us)) {
                    $ad->user        = $user->_id;    
                }
            } else {
                $ad->user        = $user->_id;
            }
            if (empty($this->status)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
            }
        } else {
            $ad->status = 6;
        }
		
        $classname = Model_Listing::getInstanceClassname((array)$this->_listing->ca);
        $translateFields = $classname::getTranslationFormField();

        $this->translate($ad, $translateFields, $classname);

        foreach ((array) $_REQUEST['category'] as $cat) {
            $tmp = new MongoId($cat);
            $ad->addCategory($tmp);
        }
        
        //$ad->category = $_POST['category'];

        $price = (int)$this->getValue('price');
        if ($price == 1) {
            $ad->price = $this->getValue('price_text_value');
        } elseif($price == 2) {
            $ad->is_free = 1;
        } else { //default to contact us even tho it should never be the case
            $ad->is_contact = 1;
        }

        $ad->area_l1                   = new MongoId($this->getValue('area_l1'));
        if ((string)$this->getValue('area_l1') == ONLINE_ONLY_AREA) {
            $ad->area_l2 = new MongoId(ONLINE_ONLY_AREA);
        }
        elseif((string)$this->getValue('area_l1') == ENTIRE_CITY) {
            $ad->area_l2 = new MongoId(ENTIRE_CITY);
        }
        else {
            $ad->area_l2 = new MongoId($this->getValue('area_l2'));
        }
                       
        
        //$ad->district   = new MongoId($this->getValue('district'));
        //$ad->area       = new MongoId($this->getValue('area'));
        $ad->tl_sc 			= (string)$this->getValue('tl_en');
        $ad->cs_sc 			= (string)$this->getValue('cs_en');
        $ad->st_sc 			= (string)$this->getValue('st_en');
        //$ad->tag = (string)$this->getValue('tag');
		if (!empty($_POST['tag']))         {$ad->tags         = array_values(explode(',',$_POST['tag']));}
        $ad->rmrk = (string)$this->getValue('remark');
        $ad->c_name = (string)$this->getValue('c_name');
        $ad->c_tel = (string)$this->getValue('c_tel');
        $ad->c_msn = (string)$this->getValue('c_msn');
        $ad->loc_flag = (string)$this->getValue('loc_flag');
        $ad->agent = (string)$this->getValue('agent');
       
        $this->continueFillup();
        if (!$preview) {
            $ad = Model_Listing_Preview::saveAsListing($ad);
            Model_Listing_Preview::remove(array('_id' => $ad->_id));            
        } else {
            //$ad = Model_Listing_Preview::convertFromListing($ad);
            $ad->forceSave();
            return $ad;
        }
        return $ad;
    }

    public function isValid($post = array())
    {
        $test1 = parent::isValid($post);
        $test2 = true;

        //Check Bad Words in Title
        if ($match = Ac_Util::checkBadWord($_POST['tl_en'])) {
            $this->getElement('tl_en')->addError('Your Ad contains banned words: '. implode(', ', $match));
            $test2 = false;
        }

        //Check Bad Words in Description
        if ($match = Ac_Util::checkBadWord($_POST['cs_en'])) {
            $this->getElement('cs_en')->addError('Your Ad contains banned words: '. implode(', ', $match));
            $test2 = false;
        }

        //Regex Title contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['tl_en'])) {
            $test2 = false;
        }
        //Regex description contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['cs_en'])) {
            $test2 = false;
        }
        
        //Price
        if ($post['price'] == '1') {
            if (empty($post['price_text_value'])){
                $test2 = false;
            }
            elseif (!is_numeric($_POST['price_text_value'])) {
                $test2 = false;
            }
        }
        

        //Exception for Online Only for Area and District
        $data = Model_Location::one(array('_id' => new MongoId($_POST['area_l1'])));
        if (!empty($data)) {
            /*if ($data->nm_en != 'Online Only') {
                if (empty($post['district'])) {
                    $this->getElement('district')->addError('This information is required');
                    $test2 = false;
                }
            }*/
            if ($data->nm_sc != 'Entire City') {
                if (empty($_POST['area_l2'])) {
                    $this->getElement('area_l2')->addError('This information is required');
                    $test2 = false;
                }
            }
        }

        //Check the two validations
        if ($test1 & $test2){
            return true;
        }
        else {
            return false;
        }
    }

    protected function continueFillup()
    {

    }

    public function __toString()
    {
        $str = '
            $j("#area_l1").change(function (event) {                
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"area", f:"area_l2_postad", id: $j("#area_l1").val() },
                    function(data) {
                        $j("#area_l2").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#area_l2"));
                        });
                         //Entire City
					    if ($j("#area_l1").val() == "4eeae63be62d6c5978000000" || $j("#area_l1").val() == "4eeeeeeeeeeeeeeeeeeeeeee" || $j("#area_l1").val() == "4aaaaaaaaaaaaaaaaaaaaaaa") {
					        $j("#area_l2").hide();
					        $j("#st_en").hide();
					    }
					    else {
					        $j("#area_l2").show();
					        $j("#st_en").show();
					    }
                    });
           });
		   
        ';
		
		$str2 = '
			$j("tl_tc_back").click(function(event) {
			alert("test");
   
			});
		
		';
        $this->view->JQuery()->addJavascript($str);
		$this->view->JQuery()->addJavascript($str2);
        return parent::__toString();
    }
}
